package controllers

import (
	"bveth"
	"encoding/json"
	"golanger.com/utils"
	"jk/jklog"
	"net/http"
	"strconv"
	"time"
)

type PageBveth struct {
	Application
}

func init() {
	App.RegisterController("bveth/", PageBveth{})
}

func (p *PageBveth) Index(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = p.LANG["bveth"]
	bveth.JKStartBroadCast()
	time.Sleep(1000 * time.Millisecond)

	jklog.L().Infoln("get lists --", len(bveth.GlobalDeviceList.Device))

	/*
		for _, v := range bveth.GlobalDeviceList.Device {
			jklog.L().Infoln("dddd -- ", v.MacAddr)
		}
	*/

	body := utils.M{}
	body["devlist"] = bveth.GlobalDeviceList.Device
	p.Body = body
}

func (p *PageBveth) Eachlist(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = p.LANG["bveth"]

	mac := p.GET["mac"]
	device := bveth.JKFindItem(mac)

	body := utils.M{}
	body["device"] = device
	p.Body = body
}

func (p *PageBveth) ControlCommand(rw http.ResponseWriter, req *http.Request) {

	status := utils.M{
		"status": 0,
	}

	var mac, ip string
	var cmdType int
	if req.Method == "POST" {
		if _, ok := p.POST["ajax"]; ok {
			mac = p.POST["mac"]
			ip = p.POST["ip"]
			cmdType, _ = strconv.Atoi(p.POST["cmdtype"])
		}
	}
	jklog.L().Debugln("ip ", ip, " mac ", mac, " type ", cmdType)
	bveth.JKControlCommon(mac, ip, cmdType)

	jklog.L().Debug("result: ", status["status"])
	result, _ := json.Marshal(status)
	rw.Write(result)
}
